<template>
  <div class="full-height full-width q-pa-md">
    <QOptionGroup
      inline
      v-model="drawType"
      :options="[
        {label: '画线', value: 'line'},
        {label: '画圆', value: 'circle'}
      ]"
    />
    <canvas
      ref="canvas"
      id="canvas"
      :height="height"
      :width="width"
      @mousedown.prevent.stop="onMouseDown"
      @mousemove.prevent.stop="onMouseMove"
      @mouseup.prevent.stop="onMouseUp"
      @mouseout.prevent.stop="onMouseOut"
    />
  </div>
</template>

<script>
export default {
  name: 'CanvasDrawer',
  props: {
    height: { type: Number, default: 400 },
    width: { type: Number, default: 400 }
  },

  data: () => ({
    drawType: 'line',
    canDraw: false,
    canvas: null,
    context: null
  }),

  mounted () {
    this.initCanvas()
  },

  methods: {
    initCanvas () {
      this.canvas = document.getElementById('canvas')
      this.context = this.canvas.getContext('2d')
      this.context.lineWidth = 5
      this.context.strokeStyle = '#2196f3'
    },

    onMouseDown (e) {
      this.canDraw = true
      const startX = e.offsetX
      const startY = e.offsetY
      this.context.beginPath()
      this.context.moveTo(startX, startY)
    },

    onMouseUp (e) {
      e = e || window.event
      this.canDraw = false
      const startX = e.offsetX
      const startY = e.offsetY
      this.context.lineTo(startX + 1, startY + 1)
      this.context.stroke()
    },

    onMouseMove (e) {
      if (this.canDraw) {
        e = e || window.event
        this.canDraw = false
        const startX = e.offsetX
        const startY = e.offsetY
        this.context.lineTo(startX + 6, startY + 6)
        this.context.stroke()
      }
    },

    onMouseOut (e) {
      console.log('TCL: onMouseOut -> e', e)
    }
  }
}
</script>
